package email

import (
	"xlq-demo/library/config"
	"crypto/tls"
	"net/smtp"
	"bytes"
	"time"
	"fmt"
	"encoding/base64"
)

type SendIn struct {
	ToEmail []string
	Subject string
	//正常内容
	Body string
	//base64格式文件数组
	Attachs []Attach
}
//定义附件格式
type Attach struct {
	Name string	//附件名字
	Body string //base64格式
}
func Send(in *SendIn) error {
	host := config.Config.Smtp.Host
	port := config.Config.Smtp.Port
	name := config.Config.Smtp.Name
	password := config.Config.Smtp.Psd
	email := config.Config.Smtp.Email
	addr := host + ":" +port

	//定义初始内容
	boundary := "ublinkemail"
	msgBuff := bytes.NewBuffer(nil)

	//写入基础header
	msgBuff.WriteString(fmt.Sprintf("From: %s<%s>\r\n",name,email))
	msgBuff.WriteString(fmt.Sprintf("To: %s\r\n",in.ToEmail))
	msgBuff.WriteString(fmt.Sprintf("Subject: %s\r\n",in.Subject))
	msgBuff.WriteString("Mime-Version: 1.0\r\n")
	msgBuff.WriteString(fmt.Sprintf("Date: %s\r\n",time.Now().String()))
	msgBuff.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\r\n\r\n",boundary))

	//正文
	msgBuff.WriteString(fmt.Sprintf("--%s\r\n",boundary))
	msgBuff.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
	msgBuff.WriteString("Content-Transfer-Encoding: base64\r\n\r\n")
	msgBuff.WriteString(base64.StdEncoding.EncodeToString([]byte(in.Body)))
	msgBuff.WriteString("\r\n\r\n")

	//写入附件
	for _,val := range in.Attachs {
		msgBuff.WriteString(fmt.Sprintf("--%s\r\n",boundary))
		msgBuff.WriteString("Content-Type: application/octet-stream\r\n")
		msgBuff.WriteString("Content-Transfer-Encoding: base64\r\n")
		msgBuff.WriteString("Content-Disposition: attachment; filename=\""+val.Name+"\"\r\n\r\n")
		msgBuff.WriteString(val.Body)
		msgBuff.WriteString("\r\n\r\n")
	}

	//内容结束
	msgBuff.WriteString(fmt.Sprintf("--%s--\r\n\r\n",boundary))

	//获取数据
	msg := msgBuff.Bytes()

	//建立tls连接
	conn,err := tls.Dial("tcp",addr,&tls.Config{InsecureSkipVerify:true})
	if err != nil {
		return err
	}
	//建立smtp客户端
	client,err := smtp.NewClient(conn,config.Config.Smtp.Host)
	if err != nil {
		return err
	}
	defer client.Close()

	//授权
	auth := smtp.PlainAuth("", email, password, host)
	if ok, _ := client.Extension("AUTH"); ok {
		if err = client.Auth(auth); err != nil {
			return err
		}
	}

	//验证发件人邮箱
	if err = client.Mail(email); err != nil {
		return err
	}

	//设置收件人
	for _, addr := range in.ToEmail {
		if err = client.Rcpt(addr); err != nil {
			return err
		}
	}

	//获取输入流
	w, err := client.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(msg)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}
	return client.Quit()

}

